package com.cqc.jdk8.Jutil.stream.collectors;

import com.cqc.eb.UserEB;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cui
 * @date 2024/6/30 13:40
 * @description 统计类函数
 **/
public class StatisticsTest {


    List<Integer> scoreList = null;
    List<UserEB> userEBList = null;

    @Before
    public void before() {
        this.getScoreList();
        this.getUserEBList();
    }

    /**
     * 求和  sum()=Collectors.summingInt(x -> x)
     */
    @Test
    public void sum() {
        int sum = scoreList.stream().mapToInt(x -> x).sum();
        Integer sum2 = scoreList.stream()
                .collect(Collectors.summingInt(x -> x));
        System.out.println(sum + "," + sum2);
    }

    /**
     * 计算平均值
     */
    @Test
    public void average() {
        Double average = scoreList.stream()
                .collect(Collectors.averagingInt(x -> x));
        System.out.println(average);
    }

    /**
     * 求总个数
     */
    @Test
    public void count() {
        Long count1 = scoreList.stream().count();
        Long count2 = scoreList.stream()
                .collect(Collectors.counting());
        System.out.println(count1 + "," + count2);
    }

    /**
     * 求最大值
     */
    @Test
    public void max() {
        userEBList.stream()
                .map(UserEB::getAge)
                .collect(Collectors.maxBy(Integer::compareTo))
                .ifPresent(System.out::println);
    }

    /**
     * 获取统计概要
     * https://mp.weixin.qq.com/s/2Cmo3XrYak1YTTW9_tqnDw
     */
    @Test
    public void f() {
        IntSummaryStatistics statistics = userEBList.stream()
                .mapToInt(UserEB::getAge)
                .summaryStatistics();
        System.out.println("getCount="+statistics.getCount());
        System.out.println("getSum="+statistics.getSum());
        System.out.println("getMax="+statistics.getMax());
        System.out.println("getMax="+statistics.getMax());
        System.out.println("getAverage="+statistics.getAverage());
    }

    private void getScoreList() {
        scoreList = new ArrayList<>();
        scoreList.add(53);
        scoreList.add(87);
        scoreList.add(98);
        scoreList.add(100);
    }


    private void getUserEBList() {
        userEBList = new ArrayList<>();
        userEBList.add(new UserEB("张三", 20));
        userEBList.add(new UserEB("李四", 21));
        userEBList.add(new UserEB("王五", 22));
        userEBList.add(new UserEB("刘诗诗", 30));
        userEBList.add(new UserEB("刘亦菲", 31));
        userEBList.add(new UserEB("古力娜扎", 28));
        userEBList.add(new UserEB("古力娜扎", 26));
    }
}
